package com.zhongyu.controller;

import com.zhongyu.config.MD5Utils;
import com.zhongyu.pojo.Role;
import com.zhongyu.pojo.User;
import com.zhongyu.service.PermissionService;
import com.zhongyu.service.UserService;
import com.zhongyu.vo.PageResult;
import com.zhongyu.vo.ResultVo;
import com.zhongyu.vo.UserVo1;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/*
员工
 */
@RestController
@RequestMapping("/renshi/user/")
public class UserController {
    @Resource
    private PermissionService permissionService;
    @Resource
    private UserService userService;
    private String msg;
 /*   @GetMapping("/list")
    public ResultVo list(UserVo userVo){
        return ResultVo.success( userService.searchByUserVo(userVo)) ;
    }*/
    @GetMapping("/list")
    public ResultVo list(){
        List<User> list= userService.searchAll();
        return  ResultVo.success(list);
    }
    @GetMapping("/list1")
    public ResultVo list1(Integer id){
        List<User> list= userService.searchById(id);
        return  ResultVo.success(list);
    }
    @GetMapping("/Cglist")
    public ResultVo Cglist(){
        List<User> list= userService.findByCgUser();
        return  ResultVo.success(list);
    }
    @GetMapping("/Xslist")
    public ResultVo Xslist(){
        List<User> list= userService.findByXsUser();
        return  ResultVo.success(list);
    }
    @GetMapping("/Kglist")
    public ResultVo Kglist(){
        List<User> list= userService.findByKgUser();
        return  ResultVo.success(list);
    }
    @GetMapping("/Sjlist")
    public ResultVo Sjlist(){
        List<User> list= userService.findByGLUser();
        return  ResultVo.success(list);
    }
     /*   @GetMapping("/search/{pageNo}/{pageSize}")
        public ResultVo search(@PathVariable Integer pageNo,@PathVariable Integer pageSize,UserVo userVo){
            PageResult pageResult=userService.searchbyUserVo(pageNo,pageSize,userVo);
            return ResultVo.success(pageResult);*/

     @GetMapping("/search/{pageNo}/{pageSize}")
     public ResultVo search(@PathVariable Integer pageNo, @PathVariable Integer pageSize, UserVo1 userVo1){
         PageResult pageResult=userService.searchAll1(pageNo,pageSize,userVo1);
         return ResultVo.success(pageResult);

        }

    @GetMapping("/search4Tree")
    public ResultVo search4Tree1(Integer id){
  // List<TreeNode> list=permissionService.search4Tree1(id);
        //return ResultVo.success(list);
        List<Role> list= permissionService.searchAll(null);
        return  ResultVo.success(list);
    }
    /*@GetMapping("/grant")
    public ResultVo grant1(@RequestParam Integer userId ,Integer roleId){
        try {
            userService.grant(userId, roleId);
            return ResultVo.success("员工授权成功！");
        }catch (RuntimeException ex){
            return ResultVo.failure("员工授权失败！",ex);
        }
    }*/
    @PostMapping("/update")
    public ResultVo update(@RequestBody User user, HttpSession session) {
        try {
            user.setModifyDate(LocalDateTime.now());
            User loginUser= (User) session.getAttribute("loginUser");
            if (loginUser!=null){
                user.setModifyBy(loginUser.getId());
            }
            userService.update(user);
            return ResultVo.success("修改员工成功!");
        }catch (Exception ex){

            return ResultVo.failure("员工修改失败!",ex);
        }
    }

    @GetMapping("/del")
    public ResultVo del(Integer id) {
        try {
            userService.del(id);
            return ResultVo.success("删除员工!");
        } catch (Exception ex) {

            return ResultVo.failure("删除员工失败！", ex);
        }
    }
    @PostMapping("/add")
    public ResultVo add(@RequestBody User user, HttpSession session){
        try {
            user.setCreationDate(LocalDateTime.now());
            User loginUser= (User) session.getAttribute("loginUser");
            if (loginUser!=null){
                user.setCreatedBy(loginUser.getId());
            }
                //加盐,并将加过盐的密码 和盐重新存入数据库中
              /*  String salt = "qwert";
                String password = MD5Utils.md5(salt+user.getPassword());
                user.setPassword(password);
                user.setSalt(salt);*/
            userService.add(user);
            msg="添加员工成功!";
            return ResultVo.success(msg);
        }catch (Exception ex){
            msg="添加员工失败!";
            return ResultVo.failure(msg,ex);
        }
    }
    @PostMapping("/updatepwd")
    @RequiresPermissions("user:pwd")
    public ResultVo updatepwd(@RequestBody User user, HttpSession session) {
         try {
             String salt = "qwert";
             String password = MD5Utils.md5(salt+user.getPassword());
             user.setPassword(password);
             user.setSalt(salt);
             userService.update(user);
             return ResultVo.success("修改员工密码成功!");
         }catch (Exception ex) {
             return ResultVo.failure("员工密码修改失败!", ex);
         }
    }
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile attach, HttpServletRequest request){
        ServletContext sc=request.getServletContext();//sc相当于jsp中的内置对象application
        String realPath=sc.getRealPath("/attach");//应用程序的根目录下的attach文件夹对应绝对路径

        File folder=new File(realPath);
        if(folder.exists()==false){  //判断attach目录是否存在，不存在会自动创建
            folder.mkdirs();
        }
        String original=attach.getOriginalFilename(); //得到上传的原始文件名
        int index=original.lastIndexOf(".");
        String suffix=original.substring(index); //得到后缀名
        String newFileName= UUID.randomUUID().toString()+suffix; //为上传文件起一个新的唯一的文件名
        File file=new File(folder,newFileName);
        try {
            attach.transferTo(file); //执行上传
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> map=new HashMap<>();
        map.put("attachPath","attach/"+newFileName);
        return ResultVo.success(map);
    }
    @PostMapping("/updateAttach")
    public ResultVo updateAttach(@RequestBody User user) {
        try {
            userService.updateById(user);
            return ResultVo.success("上传并更新工作照信息成功！");
        } catch (RuntimeException ex) {
            return ResultVo.failure("上传并更新工作照信息失败！", ex);
        }
    }

}
